package com.example.demo.listnode;

import com.example.demo.model.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * 移除重复节点
 */
public class RemoveDuplicateNodes {

    public ListNode removeDuplicateNodes(ListNode head) {
        if (head == null) return null;

        Set<Integer> set = new HashSet<>();
        set.add(head.val);

        ListNode pos = head;

        while (pos.next != null) {
            if (set.add(pos.next.val)) {
                pos = pos.next;
            } else {
                pos.next = pos.next.next;
            }
        }

        return head;
    }
}
